﻿using AbpProjectTemplate.Domain.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace AbpProjectTemplate.Components.Authorization
{
    public static class PermissionHelper
    {
        /// <summary>
        /// 权限定义,key为类型或者类型的全名
        /// </summary>
        public static IDictionary<string, PermissionDefine> PermissionDefines = new Dictionary<string, PermissionDefine>();
        //public static IDictionary<FieldInfo, PermissionDefine> FieledPermissions = new Dictionary<FieldInfo, PermissionDefine>();
        /// <summary>
        /// 获取类型的权限信息
        /// </summary>
        public static PermissionDefine GetPermissionDefine(Type type)
        {
            var name = PermissionDefine.CreateName(type);
            if (!PermissionDefines.ContainsKey(name))
            {
                PermissionDefines[name] = new PermissionDefine(type);
            }
            return PermissionDefines[name];
        }
        /// <summary>
        /// 获取字段的权限信息
        /// </summary>
        public static PermissionDefine GetPermissionDefine(FieldInfo field)
        {
            var name = PermissionDefine.CreateName(field);
            if (!PermissionDefines.ContainsKey(name))
            {
                PermissionDefines[name] = new PermissionDefine(field);
            }
            return PermissionDefines[name];
        }
        /// <summary>
        /// 获取指定对像的权限名称,只支持字符串及枚举
        /// </summary>
        public static string GetPermissionName(object val)
        {
            if (val is string)
                return val?.ToString();
            if (val is Enum @enum)
            {
                var cInfo = GetPermissionDefine(@enum.GetType().GetField(val.ToString()));
                return cInfo.Name;
            }
            throw new AppUserFriendlyException($"不支持的权限：{val}");
        }
        /// <summary>
        /// 判断权限是否为指定用户类型的权限
        /// </summary>
        public static bool HasUserType(string permissionName, UserType userType)
        {
            var define = GetPermissionDefine(permissionName);
            return define.UserType.HasFlag(userType);
        }
        /// <summary>
        /// 获取指定权限名称的权限定义
        /// </summary>
        public static PermissionDefine GetPermissionDefine(string permissionName)
        {
            if (PermissionDefines.ContainsKey(permissionName))
                return PermissionDefines[permissionName];
            throw new AppUserFriendlyException($"{permissionName}未定义。");
        }
    }
}

